package com.jmm.api.service.impl.user;

import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jmm.api.dao.user.ApiOauthMapper;
import com.jmm.api.pojo.domain.user.ApiOauthDO;
import com.jmm.api.pojo.vo.login.TokenVO;
import com.jmm.api.service.user.SocialService;
import com.jmm.api.service.user.UserService;
import com.jmm.common.constant.EnumLoginType;
import com.jmm.common.utils.Result;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 社交帐号登录 获取参数匹配
 */
@Service
@Transactional
public class SocialServiceImpl implements SocialService {
    @Autowired
    private ApiOauthMapper apiOauthMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private WxMpService wxMpService;

    private Log log = LogFactory.get();
    /**
     * h5 code get Token
     */
    @Override
    public Result<?> code2Token(String code){
        if(StrUtil.isEmpty(code)){
            return Result.fail();
        }
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = null;
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            log.error(e.getMessage());
        }
        if(wxMpOAuth2AccessToken == null){
            log.info("获取OpenId失败");
            return Result.fail();
        }
        log.info("获取用户信息：{}，使用appid匹配", JSON.toJSONString(wxMpOAuth2AccessToken));
        /**
         * 与库中数据匹配是否有用户
         * 存在->返回访问token
         * 不存在->返回当前openid构造jwt返回SocialToken 交由H5登录请求
         */
        String openId = wxMpOAuth2AccessToken.getOpenId();
        ApiOauthDO oauthDo = new ApiOauthDO();
        oauthDo.setOauthType(EnumLoginType.WECHAT.getLoginTypeCode());
        oauthDo.setOauthId(openId);
        ApiOauthDO apiOauthDO = apiOauthMapper.selectOne(new QueryWrapper<>(oauthDo));
        if(apiOauthDO != null){
            //存在 查询该对应的手机号登录用户 以便于长期保持登录
            log.info("存在用户");
            ApiOauthDO userIdDo = new ApiOauthDO();
            userIdDo.setOauthType(EnumLoginType.PHONE.getLoginTypeCode());
            userIdDo.setUserId(apiOauthDO.getUserId());
            ApiOauthDO user = apiOauthMapper.selectOne(new QueryWrapper<>(userIdDo));
            TokenVO token = userService.createToken(user);
            return Result.ok(token);
        }
        //不存在
        log.info("不存在用户");
        ApiOauthDO socialUser = new ApiOauthDO();
        socialUser.setOauthId(openId);
        TokenVO socialToken = userService.createSocialToken(socialUser);
        return Result.ok(socialToken);

    }
}
